/* (c)2010-2012 Andrea Caltroni (andrea.caltroni@pd.infn.it), INFN (www.infn.it)
 *
 * This file is part of the IGI Survey Portlet (from here on shortened to IGISP).
 * IGISP is free software: you can redistribute it and/or modify it 
 * under the terms of the GNU General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) any 
 * later version.
 *
 * IGISP is distributed in the hope that it will be useful, but WITHOUT ANY 
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with IGISP. If not, see <http://www.gnu.org/licenses/>.
 */
package it.infn.grid.liferay.survey.modules.admin.controller;


import java.io.IOException;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletModeException;
import javax.portlet.PortletPreferences;
import javax.portlet.ReadOnlyException;
import javax.portlet.ValidatorException;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.portlet.bind.annotation.ActionMapping;
import org.springframework.web.portlet.bind.annotation.RenderMapping;

import com.liferay.portal.kernel.servlet.SessionErrors;

/**
 * The controller managing the editing of the portlet's preferences.
 * 
 * @author Andrea Caltroni, andrea.caltroni@pd.infn.it, INFN
 */
@RequestMapping("EDIT")
@Controller("savePreferencesController")
public class SavePreferencesController {

    // ------------------------------------------------------------------------|
    // --- CONSTANTS ----------------------------------------------------------|
    // ------------------------------------------------------------------------|
    
    /**
     * The default number of surveys, questions and answers in the respective
     * list pages.
     */
    public static final int NUM_ITEMS_PER_PAGE = 10;
    
    /**
     * The default number of user answers in the page where those are listed.
     */
    public static final int NUM_CUST_DESCS_PER_PAGE = 15;
    
    // --- CLASS VARIABLES ----------------------------------------------------|
    // ------------------------------------------------------------------------|
    // ------------------------------------------------------------------------|

    static Logger logger = Logger.getLogger(SavePreferencesController.class);
    
    // ------------------------------------------------------------------------|
    // --- INSTANCE VARIABLES -------------------------------------------------|
    // ------------------------------------------------------------------------|

    // ------------------------------------------------------------------------|
    // --- CONSTRUCTORS -------------------------------------------------------|
    // ------------------------------------------------------------------------|

    // ------------------------------------------------------------------------|
    // --- CLASS METHODS ------------------------------------------------------|
    // ------------------------------------------------------------------------|

    // ------------------------------------------------------------------------|
    // --- INSTANCE METHODS ---------------------------------------------------|
    // ------------------------------------------------------------------------|

    /**
     * Show the preferences form (Default render phase.)
     * 
     * @param model 
     * @param prefs 
     * @param sessionStatus 
     * @return The attribute in the model defining the action of adding a new EMI 
     * document.
     */
    @RenderMapping
    public String showPreferencesForm(Model model, PortletPreferences prefs, SessionStatus sessionStatus) {
        
        model.addAttribute("noOfItemsPerPage", prefs.getValue("noOfItemsPerPage", new Integer(NUM_ITEMS_PER_PAGE).toString()));
        model.addAttribute("noOfUserDescsPerPage", prefs.getValue("noOfUserDescsPerPage", new Integer(NUM_CUST_DESCS_PER_PAGE).toString()));
        
        return "preferences";
    }

    // ------------------------------------------------------------------------|

    /**
     * Saves the preferences.
     * 
     * @param noOfItemsPerPageStr 
     * @param noOfUserDescsPerPageStr 
     * @param model 
     * @param request 
     * @param response 
     * @param prefs 
     * 
     * @throws ReadOnlyException 
     * @throws ValidatorException 
     * @throws IOException 
     * @throws PortletModeException 
     */
    @ActionMapping(params="action=savePreferences")
    public void submitPreferencesForm(@RequestParam("noOfItemsPerPage") String noOfItemsPerPageStr, 
            @RequestParam("noOfUserDescsPerPage") String noOfUserDescsPerPageStr, 
            Model model, ActionRequest request, ActionResponse response, PortletPreferences prefs) 
                    throws ReadOnlyException, ValidatorException, IOException, PortletModeException {
        
        model.addAttribute("justSaved", "FALSE");
        
        // No. of itams per page
        int noOfItemsPerPage = -1;
        if (noOfItemsPerPageStr != null && noOfItemsPerPageStr.length() > 0) {
            try {
                noOfItemsPerPage = (new Integer(noOfItemsPerPageStr)).intValue();
                if (noOfItemsPerPage < 1) {
                    // TODO not internationalized
                    SessionErrors.add(request, "noOfItemsPerPage", "Invalid number: must be greater than 1");
                }
                else {
                    // TODO can be removed?
                    prefs.reset("noOfItemsPerPage");
                    prefs.setValue("noOfItemsPerPage", noOfItemsPerPageStr);

                    prefs.store();
                    model.addAttribute("justSaved", "TRUE");
                }
            }
            catch (NumberFormatException nfExc) {
                // TODO not internationalized
                SessionErrors.add(request, "noOfItemsPerPage", "Unable to convert to number");
            }
            catch (ValidatorException vExc) {
                SessionErrors.add(request, ValidatorException.class.getName(), vExc);
            }
            
        }
        else {
            // TODO not internationalized
            SessionErrors.add(request, "noOfItemsPerPage", "No number was entered");
        }
        
        // No. of user descriptions per page
        int noOfUserDescsPerPage = -1;
        if (noOfUserDescsPerPageStr != null && noOfUserDescsPerPageStr.length() > 0) {
            try {
                noOfUserDescsPerPage = (new Integer(noOfUserDescsPerPageStr)).intValue();
                if (noOfUserDescsPerPage < 1) {
                    // TODO not internationalized
                    SessionErrors.add(request, "noOfUserDescsPerPage", "Invalid number: must be greater than 1");
                }
                else {
                    // TODO can be removed?
                    prefs.reset("noOfUserDescsPerPage");
                    prefs.setValue("noOfUserDescsPerPage", noOfUserDescsPerPageStr);

                    prefs.store();
                    model.addAttribute("justSaved", "TRUE");
                }
            }
            catch (NumberFormatException nfExc) {
                // TODO not internationalized
                SessionErrors.add(request, "noOfUserDescsPerPage", "Unable to convert to number");
            }
            catch (ValidatorException vExc) {
                SessionErrors.add(request, ValidatorException.class.getName(), vExc);
            }
            
        }
        else {
            // TODO not internationalized
            SessionErrors.add(request, "noOfUserDescsPerPage", "No number was entered");
        }
    }

    // ------------------------------------------------------------------------|

}
